<template>
  <div class="cyberpunk-chat-wrapper">
    <div class="cyberpunk-chat-container">
      <div class="cyberpunk-chat-header">
        <div class="cyberpunk-user-info">
          <span class="cyberpunk-username">{{ username }}</span>
          <span class="cyberpunk-status" :class="{ 'online': isOnline, 'offline': !isOnline }"></span>
          <el-button 
            class="cyberpunk-logout-btn"
            type="danger" 
            @click="logout()"
          >
            <span class="cyberpunk-button-text">LOGOUT</span>
            <span class="cyberpunk-button-glitch"></span>
          </el-button>
        </div>
        <div class="cyberpunk-chat-title" v-show="chatMes">
          <div class="cyberpunk-title-line"></div>
          <span>CONVERSATION WITH {{ toName }}</span>
          <div class="cyberpunk-title-line"></div>
        </div>
      </div>

      <div class="cyberpunk-chat-body">
        <!-- 聊天区域 -->
        <div class="cyberpunk-messages" id="messageArea" v-show="isShowChat">
          <div 
            class="cyberpunk-message" 
            v-for="(message, index) in historyMessage" 
            :key="index"
            :class="{
              'guest': message.fromName,
              'host': !message.fromName,
              'animate__animated animate__fadeIn': index === historyMessage.length - 1
            }"
          >
            <div class="cyberpunk-message-content" v-if="message.fromName">
              <div class="cyberpunk-message-sender">{{ message.fromName }}</div>
              <div class="cyberpunk-message-bubble guest">
                {{ message.message }}
                <div class="cyberpunk-message-tail"></div>
              </div>
            </div>
            <div class="cyberpunk-message-content" v-else>
              <div class="cyberpunk-message-sender">{{ username }}</div>
              <div class="cyberpunk-message-bubble host">
                {{ message.message }}
                <div class="cyberpunk-message-tail"></div>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="cyberpunk-input-area" v-show="isShowChat">
          <textarea
            class="cyberpunk-chat-input"
            id="context_text"
            @keyup.enter="submit"
            placeholder="TYPE YOUR MESSAGE HERE..."
            v-model="sendMessage.message"
          ></textarea>
          <button 
            class="cyberpunk-send-btn"
            @click="submit"
          >
            <span class="cyberpunk-button-text">SEND</span>
            <span class="cyberpunk-button-glitch"></span>
            <span class="cyberpunk-button-detail"></span>
          </button>
        </div>

        <!-- 好友列表 -->
        <div class="cyberpunk-sidebar">
          <div class="cyberpunk-sidebar-section">
            <div class="cyberpunk-sidebar-title">
              <span>CONTACTS</span>
              <div class="cyberpunk-sidebar-line"></div>
            </div>
            <ul class="cyberpunk-contact-list">
              <li 
                class="cyberpunk-contact-item" 
                v-for="(friend, index) in friendsList" 
                :key="index"
                @click="showChat(friend)"
              >
                <span class="cyberpunk-contact-name">{{ friend }}</span>
                <span class="cyberpunk-contact-status"></span>
              </li>
            </ul>
          </div>

          <div class="cyberpunk-sidebar-section">
            <div class="cyberpunk-sidebar-title">
              <span>SYSTEM BROADCAST</span>
              <div class="cyberpunk-sidebar-line"></div>
            </div>
            <ul class="cyberpunk-broadcast-list">
              <li 
                class="cyberpunk-broadcast-item" 
                v-for="(name, index) in systemMessages" 
                :key="index"
              >
                <span class="cyberpunk-broadcast-text">USER {{ name }} IS NOW ONLINE</span>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
    <div class="cyberpunk-scanline"></div>
  </div>
</template>

<script setup>
import { onMounted, ref, nextTick } from 'vue'
import request from '@/util/request.js'
import { ElMessage } from "element-plus";
import 'animate.css'

const webSocket = ref()

const isShowChat = ref(false)
const chatMes = ref(false)
const isOnline = ref(true)
const username = ref('')
const toName = ref('')
const sendMessage = ref({
  toName: '',
  message: ''
})
const historyMessage = ref([])
const friendsList = ref([])
const systemMessages = ref([])

onMounted(() => {
  init()
})

const init = async () => {
  await request
    .get('/user/getUsername')
    .then((response) => {
      console.log('获取用户名接口-后台返回的数据：', response)
      if (response.code === 200) {
        username.value = response.data
      }
    })
    .catch((error) => {
      console.log('获取用户名失败-错误信息：', error)
    })

  // 创建 WebSocket 对象
  webSocket.value = new WebSocket('ws://localhost:8081/chat')

  webSocket.value.onopen = onOpen
  webSocket.value.onmessage = onMessage
  webSocket.value.onclose = onClose
}

const logout = async () => { 
  await request
    .get('/user/logout')
    .then((response) => {
      console.log('登出接口-后台返回的数据：', response)
      if (response.code === 200) {
        localStorage.removeItem('token')
        ElMessage.success(response.message)
        setTimeout(() => {
          window.location.href = '/'
        }, 1000)
      }
    })
    .catch((error) => {
      console.error(error)
    })
}

const onOpen = () => {
  isOnline.value = true
}

const onClose = () => {
  isOnline.value = false
}

const onMessage = (event) => {
  let dataString = event.data
  let response = JSON.parse(dataString)

  console.log('服务端推送过来的消息：', response)

  if (response.system) {
    let names = response.message
    friendsList.value = []
    systemMessages.value = []
    for (let i = 0; i < names.length; i++) {
      if (names[i] !== username.value) {
        friendsList.value.push(names[i])
        systemMessages.value.push(names[i])
      }
    }
  } else {
    let history = sessionStorage.getItem(response.fromName);
    if (!history) {
      historyMessage.value = []
    }
    historyMessage.value.push(response)
    sessionStorage.setItem(response.fromName, JSON.stringify(historyMessage.value))
    scrollToBottom()
  }
}

const showChat = (name) => {
  toName.value = name
  let history = sessionStorage.getItem(toName.value)
  if (!history) {
    historyMessage.value = []
  } else {
    historyMessage.value = JSON.parse(history)
  }
  isShowChat.value = true
  chatMes.value = true
  nextTick(() => {
    scrollToBottom()
  })
}

const submit = () => {
  sendMessage.value.message = sendMessage.value.message.trim()

  if (!sendMessage.value.message) {
    ElMessage.error('PLEASE ENTER A MESSAGE')
    return
  }

  sendMessage.value.toName = toName.value

  historyMessage.value.push(JSON.parse(JSON.stringify(sendMessage.value)))
  sessionStorage.setItem(toName.value, JSON.stringify(historyMessage.value))

  webSocket.value.send(JSON.stringify(sendMessage.value));
  sendMessage.value.message = ''
  
  nextTick(() => {
    scrollToBottom()
  })
}

const scrollToBottom = () => {
  const messageArea = document.getElementById('messageArea')
  if (messageArea) {
    messageArea.scrollTop = messageArea.scrollHeight
  }
}
</script>

<style scoped>
/* 基础重置 */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

/* 主体样式 */
.cyberpunk-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #0a0a0a;
  background-image: 
    linear-gradient(rgba(0, 255, 255, 0.05) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0, 255, 255, 0.05) 1px, transparent 1px);
  background-size: 20px 20px;
  overflow: hidden;
  position: relative;
}

.cyberpunk-container {
  position: relative;
  width: 100%;
  max-width: 500px;
  padding: 40px;
  background: rgba(10, 10, 20, 0.8);
  border-radius: 5px;
  box-shadow: 0 0 20px rgba(0, 255, 255, 0.2),
              0 0 40px rgba(0, 255, 255, 0.1);
  border: 1px solid rgba(0, 255, 255, 0.3);
  z-index: 1;
  overflow: hidden;
}

.cyberpunk-login {
  position: relative;
  z-index: 2;
}

/* 标题样式 */
.cyberpunk-header {
  margin-bottom: 40px;
  text-align: center;
}

.cyberpunk-title {
  color: #00ffff;
  font-family: 'Courier New', monospace;
  font-size: 28px;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 5px;
  text-shadow: 0 0 10px rgba(0, 255, 255, 0.7);
  margin-bottom: 15px;
}

.cyberpunk-line {
  height: 2px;
  background: linear-gradient(90deg, transparent, #00ffff, transparent);
  margin: 0 auto;
  width: 80%;
}

/* 输入框样式 */
.cyberpunk-input-group {
  position: relative;
  margin-bottom: 30px;
}

.cyberpunk-input {
  width: 100%;
  padding: 15px 10px;
  font-size: 16px;
  color: #00ffff;
  background: transparent;
  border: none;
  border-bottom: 1px solid rgba(0, 255, 255, 0.5);
  outline: none;
  font-family: 'Courier New', monospace;
  letter-spacing: 1px;
}

.cyberpunk-input::placeholder {
  color: rgba(0, 255, 255, 0.5);
  font-family: 'Courier New', monospace;
}

.cyberpunk-highlight {
  position: absolute;
  height: 60%;
  width: 100px;
  top: 25%;
  left: 0;
  pointer-events: none;
  opacity: 0.5;
  background: rgba(0, 255, 255, 0.3);
  filter: blur(10px);
}

.cyberpunk-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 0;
  height: 2px;
  background: #00ffff;
  transition: width 0.3s ease;
}

.cyberpunk-input:focus ~ .cyberpunk-bar {
  width: 100%;
}

/* 按钮样式 */
.cyberpunk-button {
  position: relative;
  display: block;
  width: 100%;
  padding: 15px;
  margin-top: 40px;
  background: transparent;
  border: 1px solid #00ffff;
  color: #00ffff;
  font-family: 'Courier New', monospace;
  font-size: 16px;
  font-weight: bold;
  text-transform: uppercase;
  letter-spacing: 2px;
  cursor: pointer;
  overflow: hidden;
  transition: all 0.3s ease;
  z-index: 1;
}

.cyberpunk-button:hover {
  background: rgba(0, 255, 255, 0.1);
  box-shadow: 0 0 10px rgba(0, 255, 255, 0.5);
}

.cyberpunk-button-text {
  position: relative;
  z-index: 2;
}

.cyberpunk-button-glitch {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(45deg, 
    transparent 45%, 
    #ff00ff 45%, 
    #ff00ff 55%, 
    transparent 55%);
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: 1;
}

.cyberpunk-button:hover .cyberpunk-button-glitch {
  opacity: 0.3;
}

.cyberpunk-button-detail {
  position: absolute;
  bottom: 5px;
  right: 5px;
  width: 10px;
  height: 10px;
  background: #00ffff;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.cyberpunk-button:hover .cyberpunk-button-detail {
  opacity: 1;
}

/* 网格背景 */
.cyberpunk-grid {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: -1;
}

.cyberpunk-grid-line {
  position: absolute;
  background: rgba(0, 255, 255, 0.05);
}

.cyberpunk-grid-line:nth-child(1) {
  top: 33%;
  left: 0;
  width: 100%;
  height: 1px;
}

.cyberpunk-grid-line:nth-child(2) {
  top: 66%;
  left: 0;
  width: 100%;
  height: 1px;
}

.cyberpunk-grid-line:nth-child(3) {
  top: 0;
  left: 50%;
  width: 1px;
  height: 100%;
}

/* 扫描线效果 */
.cyberpunk-scanline {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    to bottom,
    transparent 0%,
    rgba(0, 255, 255, 0.05) 50%,
    transparent 100%
  );
  animation: scan 8s linear infinite;
  z-index: 3;
  pointer-events: none;
}

@keyframes scan {
  0% { transform: translateY(-100%); }
  100% { transform: translateY(100%); }
}

/* 响应式调整 */
@media (max-width: 600px) {
  .cyberpunk-container {
    padding: 30px 20px;
    margin: 0 20px;
  }
  
  .cyberpunk-title {
    font-size: 22px;
  }
}
.cyberpunk-chat-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #0a0a0a;
  background-image: 
    linear-gradient(rgba(0, 255, 255, 0.05) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0, 255, 255, 0.05) 1px, transparent 1px);
  background-size: 20px 20px;
  position: relative;
  overflow: hidden;
  font-family: 'Courier New', monospace;
}

.cyberpunk-chat-container {
  width: 90%;
  max-width: 1200px;
  height: 80vh;
  background: rgba(10, 10, 20, 0.8);
  border-radius: 5px;
  box-shadow: 0 0 20px rgba(0, 255, 255, 0.2),
              0 0 40px rgba(0, 255, 255, 0.1);
  border: 1px solid rgba(0, 255, 255, 0.3);
  display: flex;
  flex-direction: column;
  position: relative;
  z-index: 1;
  overflow: hidden;
}

.cyberpunk-chat-header {
  padding: 15px 20px;
  border-bottom: 1px solid rgba(0, 255, 255, 0.3);
  display: flex;
  flex-direction: column;
}

.cyberpunk-user-info {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.cyberpunk-username {
  color: #00ffff;
  font-weight: bold;
  margin-right: 10px;
  text-shadow: 0 0 5px rgba(0, 255, 255, 0.5);
}

.cyberpunk-status {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: auto;
}

.cyberpunk-status.online {
  background-color: #00ff00;
  box-shadow: 0 0 10px #00ff00;
}

.cyberpunk-status.offline {
  background-color: #ff0000;
  box-shadow: 0 0 10px #ff0000;
}

.cyberpunk-logout-btn {
  background: transparent;
  border: 1px solid #ff0000;
  color: #ff0000;
  padding: 5px 10px;
  font-size: 12px;
  text-transform: uppercase;
  letter-spacing: 1px;
  position: relative;
  overflow: hidden;
}

.cyberpunk-logout-btn:hover {
  background: rgba(255, 0, 0, 0.1);
  box-shadow: 0 0 10px rgba(255, 0, 0, 0.5);
}

.cyberpunk-chat-title {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6fbdf3;
  font-size: 14px;
  text-transform: uppercase;
  letter-spacing: 2px;
}

.cyberpunk-title-line {
  flex: 1;
  height: 1px;
  background: linear-gradient(90deg, transparent, #6fbdf3, transparent);
  margin: 0 10px;
}

.cyberpunk-chat-body {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.cyberpunk-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: #00ffff transparent;
}

.cyberpunk-messages::-webkit-scrollbar {
  width: 5px;
}

.cyberpunk-messages::-webkit-scrollbar-thumb {
  background-color: #00ffff;
  border-radius: 5px;
}

.cyberpunk-message {
  margin-bottom: 15px;
  display: flex;
}

.cyberpunk-message.host {
  justify-content: flex-end;
}

.cyberpunk-message.guest {
  justify-content: flex-start;
}

.cyberpunk-message-content {
  max-width: 70%;
}

.cyberpunk-message-sender {
  color: #00ffff;
  font-size: 12px;
  margin-bottom: 5px;
  text-shadow: 0 0 5px rgba(0, 255, 255, 0.3);
}

.cyberpunk-message-bubble {
  padding: 10px 15px;
  border-radius: 5px;
  position: relative;
  word-wrap: break-word;
  line-height: 1.4;
}

.cyberpunk-message-bubble.guest {
  background: rgba(0, 255, 255, 0.1);
  border: 1px solid rgba(0, 255, 255, 0.3);
  color: #00ffff;
  border-top-left-radius: 0;
}

.cyberpunk-message-bubble.host {
  background: rgba(255, 0, 255, 0.1);
  border: 1px solid rgba(255, 0, 255, 0.3);
  color: #ff00ff;
  border-top-right-radius: 0;
}

.cyberpunk-message-tail {
  position: absolute;
  width: 10px;
  height: 10px;
  top: 0;
}

.cyberpunk-message-bubble.guest .cyberpunk-message-tail {
  left: -10px;
  border-right: 10px solid rgba(0, 255, 255, 0.3);
  border-top: 10px solid transparent;
}

.cyberpunk-message-bubble.host .cyberpunk-message-tail {
  right: -10px;
  border-left: 10px solid rgba(255, 0, 255, 0.3);
  border-top: 10px solid transparent;
}

.cyberpunk-input-area {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15px;
  background: rgba(10, 10, 20, 0.9);
  border-top: 1px solid rgba(0, 255, 255, 0.3);
  display: flex;
}

.cyberpunk-chat-input {
  flex: 1;
  padding: 10px;
  background: transparent;
  border: 1px solid rgba(0, 255, 255, 0.3);
  color: #00ffff;
  font-family: 'Courier New', monospace;
  resize: none;
  outline: none;
  height: 80px;
}

.cyberpunk-chat-input:focus {
  border-color: #00ffff;
  box-shadow: 0 0 10px rgba(0, 255, 255, 0.3);
}

.cyberpunk-send-btn {
  margin-left: 10px;
  padding: 0 20px;
  background: transparent;
  border: 1px solid #00ffff;
  color: #00ffff;
  font-family: 'Courier New', monospace;
  text-transform: uppercase;
  letter-spacing: 1px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.cyberpunk-send-btn:hover {
  background: rgba(0, 255, 255, 0.1);
  box-shadow: 0 0 10px rgba(0, 255, 255, 0.5);
}

.cyberpunk-sidebar {
  width: 250px;
  border-left: 1px solid rgba(0, 255, 255, 0.3);
  background: rgba(10, 10, 20, 0.7);
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: #00ffff transparent;
}

.cyberpunk-sidebar::-webkit-scrollbar {
  width: 5px;
}

.cyberpunk-sidebar::-webkit-scrollbar-thumb {
  background-color: #00ffff;
  border-radius: 5px;
}

.cyberpunk-sidebar-section {
  padding: 15px;
  border-bottom: 1px solid rgba(0, 255, 255, 0.2);
}

.cyberpunk-sidebar-title {
  color: #00ffff;
  font-size: 14px;
  text-transform: uppercase;
  letter-spacing: 1px;
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
}

.cyberpunk-sidebar-line {
  height: 1px;
  background: linear-gradient(90deg, transparent, #00ffff, transparent);
  margin-top: 5px;
}

.cyberpunk-contact-list, .cyberpunk-broadcast-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.cyberpunk-contact-item, .cyberpunk-broadcast-item {
  padding: 8px 0;
  cursor: pointer;
  transition: all 0.3s ease;
  border-bottom: 1px solid rgba(0, 255, 255, 0.1);
}

.cyberpunk-contact-item:hover {
  background: rgba(0, 255, 255, 0.1);
}

.cyberpunk-contact-name {
  color: #00ffff;
  font-size: 13px;
}

.cyberpunk-contact-status {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #00ff00;
  margin-left: 5px;
  box-shadow: 0 0 5px #00ff00;
}

.cyberpunk-broadcast-item {
  color: #ff00ff;
  font-size: 12px;
  padding: 5px 0;
}

.cyberpunk-broadcast-text {
  display: block;
  padding: 5px;
  background: rgba(255, 0, 255, 0.05);
  border-left: 2px solid #ff00ff;
}

.cyberpunk-scanline {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    to bottom,
    transparent 0%,
    rgba(0, 255, 255, 0.05) 50%,
    transparent 100%
  );
  animation: scan 8s linear infinite;
  z-index: 2;
  pointer-events: none;
}

@keyframes scan {
  0% { transform: translateY(-100%); }
  100% { transform: translateY(100%); }
}

/* 按钮特效 */
.cyberpunk-button-text {
  position: relative;
  z-index: 2;
}

.cyberpunk-button-glitch {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(45deg, 
    transparent 45%, 
    #ff00ff 45%, 
    #ff00ff 55%, 
    transparent 55%);
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: 1;
}

.cyberpunk-button:hover .cyberpunk-button-glitch {
  opacity: 0.3;
}

.cyberpunk-button-detail {
  position: absolute;
  bottom: 5px;
  right: 5px;
  width: 10px;
  height: 10px;
  background: #00ffff;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.cyberpunk-button:hover .cyberpunk-button-detail {
  opacity: 1;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .cyberpunk-chat-container {
    width: 95%;
    height: 90vh;
  }
  
  .cyberpunk-sidebar {
    width: 200px;
  }
}

@media (max-width: 576px) {
  .cyberpunk-chat-body {
    flex-direction: column;
  }
  
  .cyberpunk-sidebar {
    width: 100%;
    border-left: none;
    border-top: 1px solid rgba(0, 255, 255, 0.3);
    max-height: 150px;
  }
  
  .cyberpunk-message-content {
    max-width: 85%;
  }
}
</style>